package com.comp6231.replica3.server;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;

import javax.swing.filechooser.FileSystemView;

import org.omg.CORBA.ORB;
import org.omg.CORBA.ORBPackage.InvalidName;
import org.omg.PortableServer.POA;
import org.omg.PortableServer.POAHelper;
import org.omg.PortableServer.POAPackage.ServantAlreadyActive;
import org.omg.PortableServer.POAPackage.WrongPolicy;

import com.comp6231.replica3.common.*;

public class ServerStarter implements Runnable {

	public static void main(String[] args) {

		new ServerStarter().startServers();

	}

	public static final String baseFolder = "replica3";

	/**
	 * start ORB and server objects
	 */
	private void startServers() {
		HashMap<String, Integer> servers = readServersInfo();

		ORB orb = ORB.init(new String[] {}, null);
		POA rootPOA;
		try {
			rootPOA = POAHelper.narrow(orb
					.resolve_initial_references("RootPOA"));

			for (String name : servers.keySet()) {
				StationServerImpl server = new StationServerImpl(name,
						servers.get(name), null);
				byte[] id = rootPOA.activate_object(server);
				org.omg.CORBA.Object ref = rootPOA.id_to_reference(id);
				String ior = orb.object_to_string(ref);
				
				PrintWriter fileWr = new PrintWriter(System.getProperty("user.dir")
						+ "/src/com/comp6231/replica3/server"
						+ "/" + name + ".ior");
				fileWr.println(ior);
				fileWr.close();
			}

			rootPOA.the_POAManager().activate();
			System.out.println("starting ORB ...");
			orb.run();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * read servers name and UDP ports from file
	 * 
	 * @return
	 */
	private HashMap<String, Integer> readServersInfo() {
		HashMap<String, Integer> servers = new HashMap<String, Integer>();
		servers.put("SPVM", 2001);
		servers.put("SPL", 2002);
		servers.put("SPB", 2003);
		return servers;
	}

	@Override
	public void run() {
		startServers();
	}

}
